// pages/my/my.js
let app = getApp();
const db = wx.cloud.database()
const _ = db.command
Page({

  /**
   * 页面的初始数据
   */
  data: {
    avatarUrl: '/pages/my/user-unlogin.png',
    nickName: '未登陆',
    gender: 0,
    logined: false
  },

  /**
   * 获取用户信息
   */
  getUserProfile: function () {
    if (!this.logined) {
      wx.getUserProfile({
        desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        lang: 'zh_CN',
        success: res => {
          console.log(res.userInfo)
          let {
            avatarUrl,
            city,
            nickName,
            gender,
            province
          } = res.userInfo
          avatarUrl = avatarUrl.split("/")
          avatarUrl[avatarUrl.length - 1] = 0;
          avatarUrl = avatarUrl.join('/');
          db.collection('user_info').add({
            data: {
              avatarUrl,
              city,
              nickName,
              gender,
              province
            },
            success: res => {
              console.log('添加用户信息成功', res)
            },
            fail: err => {
              console.log('添加用户信息失败', err)
            }
          })
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (app.globalData.openid) {
      db.collection('user_info').where({
        _openid: _.eq(app.globalData.openid)
      }).get({
        success: res => {
          console.log(res.data[0])
          let {
            avatarUrl,
            city,
            nickName,
            gender,
            province
          } = res.data[0]
          this.setData({
            avatarUrl,
            city,
            nickName,
            gender,
            province,
            logined: true
          })
        },
        fail: err => {
          wx.showToast({
            icon: 'none',
            title: '单击头像即可登陆'
          })
        }
      })
    } else {
      wx.showToast({
        icon: 'none',
        title: '单击头像即可登陆'
      })
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 2
      })
    }
  }

})